package captcha

import (
	"context"
	"gitee.com/igolang/imoney/internal/common/keys"
	"gitee.com/igolang/imoney/internal/core/client"
	"github.com/mojocn/base64Captcha"
	"image/color"
)

type Captcha struct {
	*base64Captcha.Captcha
	store *captchaStore
}

func NewCaptcha(key func(in string) *keys.Key) *Captcha {
	//driver := base64Captcha.DefaultDriverDigit
	driver := NewDriverMath(80, 240, 0, 0, &color.RGBA{
		R: 255,
		G: 255,
		B: 255,
		A: 100,
	}, nil, []string{})
	store := &captchaStore{key: key}
	return &Captcha{Captcha: base64Captcha.NewCaptcha(driver, store), store: store}
}

type captchaStore struct {
	key func(in string) *keys.Key
}

func (t *Captcha) SetKey(key func(in string) *keys.Key) {
	t.store.key = key
}

func (t *captchaStore) Set(id string, value string) error {
	rk := t.key(id)
	return client.Redis().Set(context.Background(), rk.Key, value, rk.Expire).Err()
}

func (t *captchaStore) Get(id string, clear bool) string {
	rk := t.key(id)
	val := client.Redis().Get(context.Background(), rk.Key).Val()
	if clear {
		client.Redis().Del(context.Background(), rk.Key)
	}
	return val
}

func (t *captchaStore) Verify(id, answer string, clear bool) bool {
	val := t.Get(id, clear)
	return val == answer
}
